from django.http import HttpResponse
from django.core.serializers import serialize

from ...models.chat_orders import ChatOrders

from ...utils.users import get_login_user_id
from ...utils.data_handle import chatorders_handler

import json


def orders_list(request):
    '''
    POST
    {
        "page": 1,
        "page_size": 15
    }
    status: -1:全部。0:未支付。1:已扫码。2:已支付
    获取用户账单
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 先获取用户id
        try:
            userid = get_login_user_id(request, isadmin=False)

            # all_chatorders = ChatOrders.objects.filter(user_id=userid, status=2)
            all_chatorders = ChatOrders.objects.filter(user_id=userid).order_by('-order_no')
            all_chatorders_data = chatorders_handler(all_chatorders, json_obj['page'], json_obj['page_size'])

            res_mes = {
                "code": 0,
                "data": all_chatorders_data
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        except:
            res_mes = {
                "code": 0,
                "data": {
                    "items": [],
                    "page": 1,
                    "page_size": 12,
                    "total": 0,
                    "total_page": 0
                }
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

